import { createRouter, createWebHistory } from 'vue-router'
import Home from '../components/Home.vue'
import Login from '../components/Login.vue'
import Register from '../components/Register.vue'
import MeetingList from '../components/MeetingList.vue'
import MeetingDetail from '../components/MeetingDetail.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/meetings',
    name: 'MeetingList',
    component: MeetingList,
    meta: { requiresAuth: true }
  },
  {
    path: '/meeting/:id',
    name: 'MeetingDetail',
    component: MeetingDetail,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 - 控制页面访问权限
router.beforeEach((to, from, next) => {
  const userInfo = localStorage.getItem('userInfo')
  
  // 如果页面需要认证且用户未登录，重定向到登录页
  if (to.meta.requiresAuth && !userInfo) {
    next('/login')
  } 
  // 如果已登录的用户访问登录/注册页，重定向到首页
  else if ((to.name === 'Login' || to.name === 'Register') && userInfo) {
    next('/')
  } 
  // 其他情况直接放行
  else {
    next()
  }
})

export default router